package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO dto) {
        //1.通过HttpClientUtil, 构造请求和请求参数  GET https://api.weixin.qq.com/sns/jscode2session
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");

        //2.发送请求到微信平台
        String res = HttpClientUtil.doGet(url, paramMap);

        //3.解析响应结果，获取到openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (openid == null) {
            log.warn("登录失败");
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }

        //4.如果是新用户需要完成注册
        //判断是否是新用户（根据openid查询user表）
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setName("u_"+openid.substring(5,10));
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //5.否则直接返回用户对象
        return user;
    }
}
